<template>
	<el-dialog
		title="首次登录或长时间未登录系统请修改密码"
		v-model="dialogVisible"
		width="30%"
		:close-on-press-escape="false"
		:close-on-click-modal="false"
		:show-close="false"
	>
		<el-form
     ref="loginRef"
     :rules="rules"
     :model="form">
			<el-form-item label="原密码" prop="oldPassword">
				<el-input v-model="form.oldPassword" show-password></el-input>
			</el-form-item>
			<el-form-item label="新密码" prop="newPassword">
				<el-input v-model="form.newPassword" show-password></el-input>
			</el-form-item>
			<el-form-item label="确认密码" prop="confirmPassword">
				<el-input v-model="form.confirmPassword" show-password></el-input>
			</el-form-item>
		</el-form>
		<span slot="footer" class="dialog-footer">
			<el-button @click="dialogVisible = false">取 消</el-button>
			<el-button type="primary" @click="updatePassword()">确 定</el-button>
		</span>
	</el-dialog>
</template>

<script lang="ts" setup>
import { computed, getCurrentInstance, onMounted, reactive, ref } from 'vue'
import { ElDialog, ElForm, ElFormItem, ElInput, ElButton } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import useUserStore from '@/store/modules/user'
import { updateUserPwd } from '@/api/system/user'
import {sm4Encrypt} from '@/utils/sm4'
const proxy: any = getCurrentInstance()?.proxy
const dialogVisible = ref(false)
const form = ref({
	oldPassword: '',
	newPassword: '',
	confirmPassword: ''
})
const userStore = useUserStore()
const equalToPassword = (rule, value, callback) => {
	if (form.value.newPassword !== value) {
		callback(new Error('两次输入的密码不一致'))
	} else {
		callback()
	}
}
const changePwdFlag = computed(() => {
	return userStore.changePwdFlag === '1'
})
onMounted(() => {
	if (changePwdFlag.value) {
		console.log(changePwdFlag.value)

		dialogVisible.value = true
	}
})
interface RuleForm {
  oldPassword: string
  newPassword: string
  confirmPassword: string
}
const rules = reactive<FormRules<RuleForm>>({
	oldPassword: [{ required: true, message: '旧密码不能为空', trigger: 'blur' }],
	newPassword: [
		{ required: true, message: '新密码不能为空', trigger: 'blur' },
		{
			pattern: /(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*,./<>?;:'"]+)$)^[\w~!@#$%^&*,./<>?;:'"]{8,20}/,
			message: '8到20位的字母、数字与特殊字符中至少两种的组合',
			trigger: 'blur'
		}
	],
	confirmPassword: [
		{ required: true, message: '确认密码不能为空', trigger: 'blur' },
		{ required: true, validator: equalToPassword, trigger: 'blur' }
	]
})
const updatePassword = () => {
	proxy.$refs.loginRef.validate((valid) => {
		if (valid) {
			updateUserPwd(sm4Encrypt(form.value.oldPassword),sm4Encrypt(form.value.newPassword)).then((response) => {
        proxy.$modal.msgSuccess('修改成功')
        userStore.logOut().then(() => {
				location.href = import.meta.env.VITE_PUBLIC_PATH+'index'
			})
			})
		}
	})
}
</script>
<style lang="scss" scoped></style>
